package com.mytest.provider.service.config.security.permission;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * 权限管理决断器
 *
 * @author cxb
 * @date 2019-07-29 15:56
 */
@Slf4j
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {

    /**
     * 验证请求的权限与用户的权限是否有相同的，没有就认为非法请求没有权限的路径
     * @param authentication Basicfilter里设置authentication的值
     * @param o
     * @param collection  是从权限管理器里面获取的
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if (collection == null) {
            return;
        }
        Iterator<ConfigAttribute> iterator = collection.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute c = iterator.next();
            String needPerm = c.getAttribute();
            log.info("需要验证：" + needPerm);
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                log.info(grantedAuthority.getAuthority());
                if (grantedAuthority.getAuthority().equals(needPerm.trim())) {
                    return;
                }
            }
            throw new AccessDeniedException("抱歉，您没有访问权限");
        }

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
